<template>
  <div class="user-manager">
    <div class="header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名"
          style="width: 300px; margin-right: 16px;"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <el-card>
      <!-- 使用计算属性 filteredUserList -->
      <el-table
        :data="filteredUserList"
        v-loading="loading"
        style="width: 100%"
        :default-sort="{ prop: 'registration_time', order: 'descending' }"
      >
        <el-table-column label="用户头像" width="100" align="center">
          <template #default="scope">
            <el-avatar 
              :size="50" 
              :src="getUserAvatar(scope.row)" 
              :style="{ backgroundColor: scope.row.avatar ? 'transparent' : '#e02020' }"
              fit="cover"
            >
              {{ scope.row.username.charAt(0) }}
            </el-avatar>
          </template>
        </el-table-column>

        <el-table-column prop="username" label="用户名" width="150" sortable>
          <template #default="scope">
            <span class="username">{{ scope.row.username }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="role" label="用户身份" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'primary'">
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="registration_time" label="注册时间" width="180" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.registration_time) }}
          </template>
        </el-table-column>

        <el-table-column prop="last_login_time" label="最后登录" width="180" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.last_login_time) }}
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100" align="center">
          <template #default="">
            <el-tag effect="plain" type="success">
              正常
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="warning"
              @click="viewUserDetail(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="用户详情" width="500px">
      <div v-if="selectedUser" class="user-detail">
        <div class="detail-item avatar-item">
          <div class="avatar-container">
            <el-avatar 
              :size="120" 
              :src="getUserAvatar(selectedUser)" 
              :style="{ 
                backgroundColor: selectedUser.avatar ? 'transparent' : '#e02020'
              }"
              fit="cover"
            >
              {{ selectedUser.username.charAt(0) }}
            </el-avatar>
            <!-- <div class="avatar-tips" v-if="selectedUser.avatar">
              <el-text type="info" size="small">点击头像查看大图</el-text>
            </div> -->
          </div>
        </div>
        
        <el-divider />
        
        <div class="detail-grid">
          <div class="detail-row">
            <label>用户名：</label>
            <span class="user-name">{{ selectedUser.username }}</span>
          </div>
          <div class="detail-row">
            <label>用户身份：</label>
            <el-tag :type="selectedUser.role === 'admin' ? 'danger' : 'primary'">
              {{ selectedUser.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </div>
          <div class="detail-row">
            <label>用户ID：</label>
            <span>{{ selectedUser.id }}</span>
          </div>
          <div class="detail-row">
            <label>注册时间：</label>
            <span>{{ formatDate(selectedUser.registration_time) }}</span>
          </div>
          <div class="detail-row">
            <label>最后登录：</label>
            <span>{{ formatDate(selectedUser.last_login_time) }}</span>
          </div>
          <div class="detail-row" v-if="selectedUser.avatar">
            <label>头像URL：</label>
            <div class="avatar-url">
              <el-text type="info" truncated style="max-width: 200px;">
                {{ selectedUser.avatar }}
              </el-text>
              <el-button 
                type="primary" 
                link 
                @click="copyAvatarUrl(selectedUser.avatar)"
                style="margin-left: 8px;"
              >
                复制
              </el-button>
              <el-button 
                type="success" 
                link 
                @click="viewFullAvatar(selectedUser.avatar)"
                style="margin-left: 4px;"
              >
                查看
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 头像大图预览对话框 -->
    <el-dialog v-model="avatarPreviewVisible" title="头像预览" width="400px" align-center>
      <div class="avatar-preview-content">
        <el-image
          :src="previewAvatarUrl"
          :preview-src-list="[previewAvatarUrl]"
          fit="contain"
          style="width: 100%; height: 300px;"
          :zoom-rate="1.2"
          :max-scale="7"
          :min-scale="0.2"
        >
          <template #error>
            <div class="image-error">
              <el-icon><Picture /></el-icon>
              <div>图片加载失败</div>
            </div>
          </template>
        </el-image>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { startRequest, RequestPath } from '../base/RequestWork';

// 响应式数据
const userList = ref<any[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchKeyword = ref('');
const detailDialogVisible = ref(false);
const selectedUser = ref<any>(null);
const avatarPreviewVisible = ref(false);
const previewAvatarUrl = ref('');

// 计算属性：过滤用户列表 - 确保这个计算属性存在
const filteredUserList = computed(() => {
  if (!searchKeyword.value) {
    return userList.value;
  }
  return userList.value.filter(user => 
    user.username.toLowerCase().includes(searchKeyword.value.toLowerCase())
  );
});
// 获取用户头像
const getUserAvatar = (user: any) => {
  if (user.avatar && user.avatar !== '') {
    return user.avatar;
  }
  return '';
};
// 查看完整头像
const viewFullAvatar = (avatarUrl: string) => {
  previewAvatarUrl.value = avatarUrl;
  avatarPreviewVisible.value = true;
};
// 加载用户数据
const loadUserData = async () => {
  loading.value = true;
  try {
    const offset = (currentPage.value - 1) * pageSize.value;
    const response = await startRequest(RequestPath.usersList, 'GET', {
      offset: offset,
      limit: pageSize.value
    });
    console.log('用户列表响应:', response.data);
    if (response.data.msg === 'ok' && response.data.datas) {
      userList.value = response.data.datas;
      total.value = response.data.total || 0;
      ElMessage.success(`成功加载 ${userList.value.length} 条用户数据`);
    } else {
      ElMessage.error(response.data.error || '获取用户列表失败');
    }
  } catch (error: any) {
    console.error('加载用户数据失败:', error);
    ElMessage.error(error.response?.data?.error || '网络错误，请检查接口路径');
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  // 搜索时使用计算属性过滤，不需要重新加载数据
};

// 刷新数据
const refreshData = () => {
  currentPage.value = 1;
  searchKeyword.value = '';
  loadUserData();
  ElMessage.info('数据已刷新');
};

// 分页大小改变
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  loadUserData();
};

// 当前页改变
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  loadUserData();
};

// 查看用户详情
const viewUserDetail = (user: any) => {
  selectedUser.value = user;
  detailDialogVisible.value = true;
};

// 复制头像URL
const copyAvatarUrl = (url: string) => {
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('头像URL已复制到剪贴板');
  }).catch(() => {
    ElMessage.error('复制失败');
  });
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-';
  try {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
  } catch (error) {
    return dateString;
  }
};

// 生命周期
onMounted(() => {
  loadUserData();
});
</script>

<style scoped>
.user-manager {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  align-items: center;
}

.username {
  font-weight: 600;
  color: #333;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}

.user-detail {
  padding: 10px 0;
}

.avatar-item {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.avatar-container {
  text-align: center;
}

/* .avatar-tips {
  margin-top: 8px;
} */

.detail-grid {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-row {
  display: flex;
  align-items: center;
  min-height: 32px;
}

.detail-row label {
  width: 100px;
  font-weight: 600;
  color: #666;
  margin-right: 16px;
  text-align: right;
  flex-shrink: 0;
}

.detail-row span {
  flex: 1;
  color: #333;
}

.user-name {
  font-weight: 600;
  font-size: 16px;
  color: #1890ff;
}

.avatar-url {
  display: flex;
  align-items: center;
  flex: 1;
}

.avatar-preview-content {
  text-align: center;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #999;
}

.image-error .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

:deep(.el-avatar) {
  flex-shrink: 0;
}

:deep(.el-table .cell) {
  text-align: center;
}

:deep(.el-divider) {
  margin: 20px 0;
}
</style>